package com.weetop.cfw.register

import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.EncryptUtils
import com.kongzue.dialog.v3.BottomMenu
import com.weetop.cfw.MainActivity
import com.weetop.cfw.R
import com.weetop.cfw.base.presenter.imp.PasswordLogInPresenterImp
import com.weetop.cfw.base.presenter.imp.RegisterPresenterImp
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import com.weetop.cfw.base.view.PasswordLogInView
import com.weetop.cfw.base.view.RegisterView
import com.weetop.cfw.bean.GeneralCodeTableBean
import com.weetop.cfw.bean.LogInBean
import com.weetop.cfw.bean.VerificationCodeBean
import com.weetop.cfw.constants.UrlConstants
import com.weetop.cfw.event.UpdateUserInfoEvent
import com.weetop.cfw.other.CommonWebViewActivity
import com.weetop.cfw.utils.EventBusUtils
import com.weetop.cfw.utils.MMKVUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_register.*
import java.util.concurrent.TimeUnit

/**
 * 注册界面
 */
class RegisterActivity : CommonBaseActivity(), View.OnClickListener, RegisterView,
    PasswordLogInView {


    private lateinit var registerPresenterImp: RegisterPresenterImp
    private lateinit var passwordLogInPresenterImp: PasswordLogInPresenterImp


    private var dispose: Disposable? = null//接触Observable与Activity的绑定

    private var source: Int = -1//用户来源
    private var IsSelect: Int = 0


    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.textLogIn -> ActivityUtils.finishActivity(this)
            R.id.textBeginRegister -> {
                if (IsSelect == 0) {
                    Toast.makeText(context, "请仔细阅读并同意用户协议", Toast.LENGTH_SHORT).show()
                    return
                }
                registerPresenterImp.register(
                    this@RegisterActivity,
                    editUserName.text.toString().trim(),
                    editPhoneNumber.text.toString().trim(),
                    editVerificationCode.text.toString().trim(),
                    EncryptUtils.encryptMD5ToString(editLogInPassword.text.toString().trim())
                        .toLowerCase(),
                    EncryptUtils.encryptMD5ToString(editMakeSurePassword.text.toString().trim())
                        .toLowerCase(),
                    source
                )
            }
            R.id.imageRegisterBack -> ActivityUtils.finishActivity(this)
            R.id.textUseProtocol -> CommonWebViewActivity.startCommonWebViewActivity(
                this,
                UrlConstants.use_protocol_web_url
            )
            R.id.textPrivacyPolicy -> CommonWebViewActivity.startCommonWebViewActivity(
                this,
                UrlConstants.privacy_policy_web_url
            )
            R.id.textGetVerificationCode -> registerPresenterImp.getVerificationCode(
                this,
                editPhoneNumber.text.toString().trim()
            )
            R.id.textSource -> registerPresenterImp.sourceList(this)
            R.id.select -> {
                if (IsSelect == 0) {
                    IsSelect = 1
                    select.setImageResource(R.mipmap.select_t);
                } else {
                    IsSelect = 0
                    select.setImageResource(R.mipmap.select_f);
                }
            }
        }
    }

    override fun getLayoutId() = R.layout.activity_register

    override fun initView(savedInstanceState: Bundle?) {
        registerPresenterImp = RegisterPresenterImp()
        passwordLogInPresenterImp = PasswordLogInPresenterImp()
        registerPresenterImp.attachView(this)
        passwordLogInPresenterImp.attachView(this)
        setViewsOnClickListener(
            this,
            textSource,
            textLogIn,
            imageRegisterBack,
            textUseProtocol,
            textPrivacyPolicy,
            textBeginRegister,
            textGetVerificationCode,
            select
        )
    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    /**
     * 注册成功
     */
    override fun registerSuccess(message: String?) {
        showNativeShortToast(message)
        passwordLogInPresenterImp.passwordLogIn(
            this@RegisterActivity,
            editPhoneNumber.text.toString().trim(),
            EncryptUtils.encryptMD5ToString(editLogInPassword.text.toString().trim()).toLowerCase()
        )
    }

    override fun logInSuccess(logInBean: LogInBean?) {
        if (logInBean != null) {
            showNativeShortToast("登录成功")
            MMKVUtils.saveToken(logInBean.token)
            MMKVUtils.saveUlevel(logInBean.ulevel)
            EventBusUtils.post(logInBean)
            EventBusUtils.post(UpdateUserInfoEvent())
            ActivityUtils.finishActivity(this)
            ActivityUtils.startActivity(MainActivity::class.java)
        }
    }

    /**
     * 注册失败
     */
    override fun registerFailed(message: String?) {

    }


    override fun getVerificationCodeSuccess(verificationCodeBean: VerificationCodeBean?) {
        showNativeShortToast(verificationCodeBean?.message)
        dispose = Observable.interval(1, TimeUnit.SECONDS)
            .take(61)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if ((60 - it) == 0L) {
                    textGetVerificationCode.text = "发送验证码"
                    textGetVerificationCode.setTextColor(ColorUtils.getColor(R.color.c_1381CC))
                    textGetVerificationCode.isEnabled = true
                } else {
                    textGetVerificationCode.isEnabled = false
                    textGetVerificationCode.setTextColor(ColorUtils.getColor(R.color.secondary_text_color))
                    textGetVerificationCode.text = "${60 - it}秒后重新发送"
                }
            }
    }

    override fun getVerificationCodeFailed(verificationCodeBean: VerificationCodeBean?) {
        showNativeShortToast(verificationCodeBean?.message)
    }

    /**
     * 来源列表获取成功
     */
    override fun sourceListGetSuccess(generalCodeTableBean: GeneralCodeTableBean?) {
        if (generalCodeTableBean != null) {
            val sourceList = ArrayList<String>()
            for (item in generalCodeTableBean.data) {
                sourceList.add(item.codename)
            }
            BottomMenu.show(this, sourceList) { text, index ->
                source = generalCodeTableBean.data[index].codeid

                textSource.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                textSource.text = text
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        registerPresenterImp.detachView()
        if (dispose != null && !dispose!!.isDisposed) {
            dispose!!.dispose()
        }
    }
}
